package logic

import (
	"context"
	"gozerogateway/common/errorx"
	"gozerogateway/rpc/common/MD5"
	"gozerogateway/rpc/model/appmodel"
	"gozerogateway/rpc/tenant/internal/svc"
	"gozerogateway/rpc/tenant/tenantclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type AppAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAppAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AppAddLogic {
	return &AppAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AppAddLogic) AppAdd(in *tenantclient.AppAddHttpReq) (*tenantclient.AppAddHttpResp, error) {
	// todo: add your logic here and delete this line

	if err := l.svcCtx.AppModel.FindOneByAppId(l.ctx, in.AppID); err == nil {
		return nil, errorx.NewDefaultError("appid is exist")
	}

	if in.Secret == "" {
		in.Secret = MD5.MD5(in.AppID) //or base timestamp
	}

	l.svcCtx.AppModel.Insert(l.ctx, &appmodel.GatewayApp{
		AppId:    in.AppID,
		Name:     in.Name,
		Secret:   in.Secret,
		WhiteIps: in.WhiteIPS,
		Qps:      in.Qps,
		Qpd:      in.Qpd,
	})
	return &tenantclient.AppAddHttpResp{
		Isok: 1,
	}, nil
}
